const mysql = require("mysql2/promise");
const { ...config } = require('../config/index')
const pool = mysql.createPool({
  host: config.mysqlConfig.host,
  port: config.mysqlConfig.port,
  user: config.mysqlConfig.user,
  password: config.mysqlConfig.password,
  database: config.mysqlConfig.database,
  charset: "utf8mb4",
});

const db = {
  getWriter() {
    return pool.getConnection();
  },
  query(connection, sql, params) {
    try {
      return connection.query(sql, params);
    } finally {
      connection.release();
    }
  },

  async reader(sql, params) {
    const conn = await pool.getConnection();
    try {
      const [result] = await db.query(conn, sql, params);
      return result;
    } catch (err) {
      console.error(`db err release: ${err}`);
      throw err;
    }
  },

  async writer(sql, params) {
    const conn = await pool.getConnection();
    try {
      const [rows, fields] = await db.query(conn, sql, params);
      return rows;
    } catch (err) {
      console.error(`db err release: ${err}`);
      throw err;
    }
  },
};

module.exports = db;
